package com.mjk.common.web.getway.restful.prototal.ws.soap.config;

import com.mjk.common.base.constns.BeeCommonConstns;
import com.mjk.common.tools.springextend.BeeApplicationListener;
import com.mjk.common.util.ClassUtil;
import com.mjk.common.web.getway.restful.prototal.ws.soap.annotation.BeeSoap;
import com.mjk.common.web.getway.restful.prototal.ws.soap.utils.SoapUtils;
import groovy.lang.GroovyClassLoader;
import jakarta.servlet.Servlet;
import org.apache.cxf.Bus;
import org.apache.cxf.bus.spring.SpringBus;
import org.apache.cxf.transport.servlet.CXFServlet;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.ContextRefreshedEvent;

import java.util.Set;

@Configuration
public class BeeSoapConfig implements BeeApplicationListener {

	@Bean
	public ServletRegistrationBean<Servlet> cxfServlet() {
        return new ServletRegistrationBean<>(
                new CXFServlet(), "/webservice/*");
	}

	@Bean(name = Bus.DEFAULT_BUS_ID)
	public SpringBus springBus() {
		return new SpringBus();
	}
	@Override
	public void doApplicationEvent(ContextRefreshedEvent event) {
		Set<Class<?>> clazzs = cn.hutool.core.util.ClassUtil.scanPackageByAnnotation(BeeCommonConstns.BASE_PACKAGE, BeeSoap.class);
//		Set<Class<?>> clazzs = ClassUtil.scanPackageByAnnotation(BeeCommonConstns.BASE_PACKAGE, true, BeeSoap.class);
        //BeeSoapInvcationHandler invcation = event.getApplicationContext().getBean(BeeSoapInvcationHandler.class);
		ApplicationContext parent = event.getApplicationContext().getParent();
		ApplicationContext superParent = null;
		if(null!=parent){
			superParent = parent.getParent();
		}
		if (parent == null|| superParent == null) {
			for (Class<?> clazz : clazzs) {
					BeeSoap soap = clazz.getAnnotation(BeeSoap.class);
					SoapUtils.publish(clazz,soap.path(),new GroovyClassLoader());
			}
		}
	}
}
